package com.kyzh.core.pager.me.settings


import android.os.Bundle
import android.text.Html
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.gushenge.core.base.fragment.BaseFragment
import com.gushenge.core.beans.Deal
import com.gushenge.core.dao.GlobalKeys
import com.gushenge.core.impls.WealImpl
import com.gushenge.core.listeners.ResultListener
import com.kyzh.core.R
import com.kyzh.core.activities.BrowserActivity
import com.kyzh.core.uis.alert
import com.kyzh.core.utils.startActivity
import kotlinx.android.synthetic.main.bottom_button.*
import kotlinx.android.synthetic.main.fragment_settle.*
import kotlinx.android.synthetic.main.game_detail_deal_item.*
import org.jetbrains.anko.support.v4.toast

/**
 * A simple [Fragment] subclass.
 */
class SettleFragment(val deal: Deal) : BaseFragment() {


    private var canSelect = false
    var payArray   = mutableListOf<Pay>()
//    val payArray = arrayListOf(/*Pay(R.drawable.icon_pt,"余额支付",false),*/
//            Pay(R.drawable.icon_ptb_pay, getString(R.string.ptbPay), false),
//            Pay(R.drawable.icon_wxpay, getString(R.string.wechatPay), false),
//            Pay(R.drawable.icon_alipay_, getString(R.string.alipay), false))
    private val payAdapter = InnerAdapter(R.layout.settle_pay_item, payArray)
    var oid = ""
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_settle, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        initView()

    }

    private fun initView() {
        payArray.add(Pay(R.drawable.icon_ptb_pay, getString(R.string.ptbPay), false))
        payArray.add( Pay(R.drawable.icon_wxpay, getString(R.string.wechatPay), false))
        payArray.add(Pay(R.drawable.icon_alipay_, getString(R.string.alipay), false))
        initKnow()
        initTip()
        recyclerView.layoutManager = object : LinearLayoutManager(context) {
            override fun canScrollHorizontally(): Boolean {
                return false
            }

            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        payArray[0].check = true
        recyclerView.adapter = payAdapter
        payAdapter.setOnItemClickListener { adapter, view, position ->
            reset()
            payArray[position].check = true
            payAdapter.notifyDataSetChanged()
        }

        time.text = "${getString(R.string.addedTime)}:${deal.time}"
        Glide.with(requireActivity()).load(deal.image).into(image)
        name.text = deal.name
        content.text = deal.introduction
        price.text = deal.money

        btBottom.text = getString(R.string.surePay)
        btBottom.setOnClickListener {
            val type = getPayType() + 1
            pay(type, deal.id, deal.money)
        }
    }

    private fun pay(type: Int, id: String, money: String) {
        WealImpl.dealSettle(type, id, money, object : ResultListener {
            override fun error(error: String) {
                toast(error)
            }

            override fun success(bean: Any) {
                if (type < 2) {
                    toast(getString(R.string.buySuccess))
                    requireActivity().finish()
                } else {
                    canSelect = true
                    bean as Deal
                    val url = bean.url
                    oid = bean.oid
                    startActivity<BrowserActivity>(GlobalKeys.TITLE to getString(R.string.payCenter), GlobalKeys.LINK to url, GlobalKeys.KEY to true)
                }
            }
        })
    }

    public fun selectOrder() {
        if (canSelect) {

            WealImpl.dealOrderSelect(oid, object : ResultListener {
                override fun error(error: String) {
                    canSelect = false
                    alert(title = getString(R.string.pleaseNote), message = error, yesButtonText = getString(R.string.refresh), noButtonText = getString(R.string.close),{
                        canSelect = true
                        selectOrder()
                    },{})
                }

                override fun error() {
                    canSelect = false
                    alert(title = getString(R.string.pleaseNote), message = getString(R.string.checkBillFailed), yesButtonText = getString(R.string.refresh), noButtonText = getString(R.string.rePay),{
                        canSelect = true
                        selectOrder()
                    },{})
                }

                override fun success() {
                    canSelect = false
                    alert(getString(R.string.paySuccess), null, getString(R.string.close), null,{
                        requireActivity().finish()
                    },{})
                }
            })
        }
    }

    private fun getPayType(): Int {
        for (i in 0 until payArray.size) {
            if (payArray[i].check) {
                return i
            }
        }
        return 0
    }

    private fun reset() {
        for (i in payArray) {
            i.check = false
        }
    }


    private inner class InnerAdapter(layout: Int, beans: MutableList<Pay>) : BaseQuickAdapter<Pay, BaseViewHolder>(layout, beans) {
        override fun convert(helper: BaseViewHolder, item: Pay) {
            item?.apply {
                helper.setImageResource(R.id.payIcon, icon)
                        .setText(R.id.payText, text)
                        .setImageResource(R.id.payCheck, if (check) R.drawable.settle_checked else R.drawable.settle_nocheck)
            }
        }
    }

    data class Pay(var icon: Int,
                   var text: String,
                   var check: Boolean)

    private fun initKnow() {

        val str = "1.${getString(R.string.buyKnow1)}<font color=\"#EC0B0B\">" + getString(R.string.buyKnow2) +
                "</font>;<br/>2.${getString(R.string.buyKnow3)};<br/>3.${getString(R.string.buyKnow4)}<font color=\"#EC0B0B\">" +
                "${getString(R.string.buyKnow5)}" + "</font>;<br/>4.${getString(R.string.buyKnow6)}<br/>5.${getString(R.string.buyKnow7)}，<font color=\"#EC0B0B\">" + getString(R.string.buyKnow8) + "</font>。"
        tvKnow.text = Html.fromHtml(str)
    }


    private fun initTip() {
        alert(getString(R.string.sellKnow), getString(R.string.sellKnow1), getString(R.string.buyNow), getString(R.string.giveUpBuy),{},{
            requireActivity().finish()
        }).setCancelable(false)
    }

}
